<?php
/**
 * Created by PhpStorm.
 * User: xieky
 * Date: 2017/6/15
 * Time: 12:26
 */

namespace console\controllers;


use common\entities\myhtsq\ContractDeveloperEntity;
use common\entities\myhtsq\ContractDocumentEntity;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\IncomeItemLogRepository;
use common\services\myhtsq\ErpInterfaceService;
use Guzzle\Common\Exception\ExceptionCollection;
use yii\base\Exception;
use yii\console\Controller;
use common\helpers\CurlHelper;
use common\helpers\JWTHelper;
use common\entities\myhtsq\ContractManageEntity;
use common\entities\myhtsq\ContractCaibaoDetailEntity;
use common\entities\myhtsq\ContractSupplierEntity;
use common\entities\myhtsq\ContractPayinfoEntity;
use common\entities\myhtsq\ApplicationInfoEntity;
use common\entities\myhtsq\ApplicationPriceEntity;
use common\entities\myhtsq\InvoiceEntity;
use common\entities\myhtsq\BussAccountTypesEntity;
use common\entities\myhtsq\InvoiceSummaryEntity;
use common\entities\myhtsq\ContractProductEntity;
use common\entities\myhtsq\ContractPayoverEntity;
use common\entities\myhtsq\ContractTenantRelationEntity;
use common\entities\myhtsq\DocumentEntity;
use common\entities\myhtsq\ContractFileEntity;
use common\repositories\myhtsq\ContractFlowCodeRepository;
use common\repositories\myhtsq\ContractRevenueRepository;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\entities\myhtsq\ContractRevenueEntity;
use common\support\StringHelper;
use common\entities\ConfigEntity;
use console\controllers\ConstInfo;
use common\support\OSSUploader;
use common\services\myhtsq\ContractService;
use Yii;

class CaigouApiController extends Controller
{
    /**
     * 获取云采购供应商信息数据
     * @return string|void
     */
    public function actionSyncSuppliers()
    {
        $confUrl = \Yii::$app->params['MYCAIGOU_API_URL'];
        $apiUrl = $this->getUrl($confUrl, 'get-supplier-info', 'bgtime', 'endtime');
        $getdata = CurlHelper::getCurlData($apiUrl, false, false);

        if (empty($getdata)) {
            print('远程接口请求结果异常!' . $apiUrl . PHP_EOL);
            return;
        }
        if (empty($getdata->data)) {
            print('本次查询无数据:' . $apiUrl) . PHP_EOL;
            return;
        }

        //获取供应商信息
        $supplierinfos = $getdata->data;

        print_r($supplierinfos);

        foreach ($supplierinfos as $item) {
            $contractSupplier = ContractSupplierEntity::find()->where(['supplier_id' => $item->supplier_id])->one();
            if (!empty($contractSupplier)) {
                print('ID为:' . $item->supplier_id . '的供应商已存在.' . PHP_EOL);
                continue;
            }
            $contractSupplier = new ContractSupplierEntity();
            $contractSupplier->supplier_id = $item->supplier_id;
            $contractSupplier->short_name = $item->short_name;
            $contractSupplier->company_name = $item->company_name;
            $contractSupplier->sys_created_time = $item->created_time;
            if ($contractSupplier->save()) {
                print('保存成功:' . $contractSupplier->supplier_id . PHP_EOL);
            }
        }

        return '';
    }

    /**
     * 同步云采购釆宝订单及所有支付信息信息,半小时执行一次
     */
    public function actionSyncCaigouOrderInfo()
    {
        $confUrl = \Yii::$app->params['MYCAIGOU_API_URL'];
        $apiUrl = $this->getUrl($confUrl, 'get-order-info', 'bgtime', 'endtime');
        $getdata = CurlHelper::getCurlData($apiUrl, false, false);

        if (empty($getdata)) {
            print('远程接口请求结果异常!' . $apiUrl . PHP_EOL);
            return;
        }
        if (empty($getdata->data)) {
            print('本次查询无数据:' . $apiUrl) . PHP_EOL;
            return;
        }
        //获取待处理订单
        $orderinfos = $getdata->data;

        print_r($orderinfos);

        foreach ($orderinfos as $item) {
            $contractManage = ContractPayinfoEntity::find()->where(['pay_order_id' => $item->pay_order_id])->one();
            if (!empty($contractManage)) {
                print('订单ID为:' . $item->pay_order_id . '的支付信息已存在.' . PHP_EOL);
                continue;
            }

            $contractId = StringHelper::uuid();   //新建合同ID
            $producename = $item->business_type;   //业务类型,'云采购采宝'
            $nowtime = ConfigEntity::getDbNowDate();

            //保存支付信息
            $payinfo = new ContractPayinfoEntity();
            $payinfo->payinfo_id = StringHelper::uuid();
            //if($producename == '云采购采宝') $payinfo ->contract_id = $contractId;
            $payinfo->pay_amount = $item->pay_money / 100;
            $payinfo->pay_time = $item->pay_time;
            $payinfo->user_name = $item->create_user;
            $payinfo->company_name = $item->pay_company;
            $payinfo->pay_order_id = $item->pay_order_id;
            $payinfo->order_code = $item->pay_order_id;
            $payinfo->pay_way = $item->pay_way;
            $payinfo->product_name = $producename;
            $payinfo->isNeedInvoice = 0;   //釆宝未与商城挂接,暂无法获取发票
            $payinfo->created_on = $nowtime;
            $payinfo->created_by = 'schedule';
            if ($payinfo->save()) {
                print('支付信息保存成功:' . $payinfo->contract_id . PHP_EOL);
            }

            //只有釆宝的订单才产生合同信息
//            if($producename == '云采购采宝'){
//                //保存合同基本信息
//                $contractManage = new ContractManageEntity();
//                $contractManage ->business_type_id = ConstInfo::CONTRACT_BUSSINESS_TYPE_YCGCB;
//                $contractManage ->contract_code = ContractFlowCodeRepository::getContractCode();   //生成合同编码
//                $contractManage ->contract_id = $contractId;   //新建合同ID
//                $contractManage ->supplier_id = $item->pay_company_id;     //供应商ID
//                $contractManage ->supplier_name = $item->pay_company;
//                $contractManage ->customer_name = $item->pay_company;
//                $contractManage ->customer_full_name = $item->pay_company;
//                $contractManage ->orderid  = $item ->pay_order_id;    //订单号,非商城订单编码,无法与发票系统打通
//                $contractManage ->sign_amount = $item->pay_money;
//                $contractManage ->sign_date = $item->pay_time;
//                $contractManage ->effect_date = $item->pay_time;
//                $contractManage ->input_date = $item->pay_time;
//                $contractManage ->give_work_day = 0;
//                $contractManage ->develop_work_day=0;
//                $contractManage ->implement_work_day=0;
//                $contractManage ->contract_property_id = '037b890b-5ae3-11e7-9f96-000c29310f8b';    //云链直销,转换过为性质表的ID
//                $contractManage ->company_id = 'a3d3a00a-4b29-11e7-af9f-005056a65fd7';  //明源云链,转换为公司ID
//                $contractManage ->contract_status = 2;
//                $contractManage ->created_by = 'schedule';
//                $contractManage ->created_on = $nowtime;
//                $contractManage ->contract_remark = $producename.' 订单生成合同';
//
//                if($contractManage->save()){
//                    print('保存成功:'.$contractManage ->contract_id.PHP_EOL);
//                }
//            }
        }
        return $apiUrl;
    }

    /**
     * 按月获取釆宝信息,每月28日执行,执行包含上月28到本月27之间的数据
     */
    public function actionGetCaibaoDataByMonth()
    {
        $nowtime = ConfigEntity::getDbNowTimestamp();
        $lastmonth = date('Y-m', strtotime('-1 month', $nowtime));
        $lastmonthfirstday = $lastmonth . '-28 00:00:00';
        $lastmonthfirstdayurl = $lastmonth . '-28%2000:00:00';

        $thismonth = date('Y-m', $nowtime);
        $thismonthlastday = $thismonth . '-27 23:59:59';
        $thismonthlastdayurl = $thismonth . '-27%2023:59:59';
        //$lasttwomonth = date('Y-m',strtotime('-2 month',$nowtime));

        $confUrl = \Yii::$app->params['MYCAIGOU_API_URL'];
        $apiUrl = $confUrl . 'get-caibao-by-month?bgtime=' . $lastmonthfirstdayurl . '&endtime=' . $thismonthlastdayurl;
        $getdata = CurlHelper::getCurlData($apiUrl, false, false);

        if (empty($getdata)) {
            print('远程接口请求结果异常!' . $apiUrl . PHP_EOL);
            return;
        }
        if (empty($getdata->data)) {
            print('本次查询无数据:' . $apiUrl) . PHP_EOL;
            return;
        }
        //获取待处理订单
        $monthtotal = $getdata->data->monthtotal;
//        $incoices = $getdata->data->invoice;
        $details = $getdata->data->detail;

        print_r($monthtotal);

        //判断本月的合同是否已经产生,不允许重复生成合同
        $contract = ContractManageRepository::getContractBySuppliername('釆宝' . $thismonth . '合同');
        if (!empty($contract)) {
            print($thismonth . '月份釆宝合同已存在:' . PHP_EOL);
            return;
        }
        $beginremainamount = 0;
        $contract2 = ContractManageRepository::getContractBySuppliername('釆宝' . $thismonth . '合同');
        if (!empty($contract2)) {
            $beginremainamount = $contract2->end_remain_amount;
        }
        //保存合同基本信息
        $contractid = StringHelper::uuid();
        $contractManage = new ContractManageEntity();
        $contractManage->business_type_id = ConstInfo::CONTRACT_BUSSINESS_TYPE_YCGCB;
        $contractManage->contract_code = ContractFlowCodeRepository::getContractCode();   //生成合同编码
        $contractManage->contract_id = $contractid;   //新建合同ID

        $thismonthrechargemoney = empty($monthtotal[0]->this_month_recharge_money) ? 0 : $monthtotal[0]->this_month_recharge_money;
        $thismonthconsumemoney = empty($monthtotal[0]->this_month_consume_money) ? 0 : $monthtotal[0]->this_month_consume_money;

        $contractManage->supplier_name = '釆宝' . $thismonth . '合同';
        $contractManage->begin_remain_amount = $beginremainamount;
        $contractManage->end_remain_amount = ($beginremainamount + $thismonthrechargemoney - $thismonthconsumemoney);
        $contractManage->this_month_recharge_amount = $thismonthrechargemoney;
        $contractManage->sign_amount = $thismonthrechargemoney;
        $contractManage->this_month_consume_amount = $thismonthconsumemoney;

        $contractManage->sign_date = $thismonthlastday;
        $contractManage->effect_date = $thismonthlastday;
        $contractManage->input_date = $thismonthlastday;

        $contractManage->contract_property_id = '037b890b-5ae3-11e7-9f96-000c29310f8b';    //云链直销,转换过为性质表的ID
        $contractManage->company_id = 'a3d3a00a-4b29-11e7-af9f-005056a65fd7';  //明源云链,转换为公司ID
        $contractManage->contract_status = 2;
        $contractManage->created_by = 'schedule';
        $contractManage->created_on = ConfigEntity::getDbNowDate();
        $contractManage->contract_remark = '执行时间:' . ConfigEntity::getDbNowDate() . ' 釆宝按月生成合同';

        if ($contractManage->save()) {
//            foreach($incoices as $invoice){
//                $inv = new InvoiceEntity();
//                $inv->contract_id = $contractid;
//            }

            //保存合同明细,支持下载
            foreach ($details as $item) {
                $caibaodetail = new ContractCaibaoDetailEntity();
                $caibaodetail->detail_id = StringHelper::uuid();
                $caibaodetail->contract_id = $contractid;
                $caibaodetail->user_name = $item->name;
                $caibaodetail->company_name = $item->company_name;
                $caibaodetail->consume_amount = $item->sumcaibao;
                $caibaodetail->balance = $item->balance;
                $caibaodetail->created_on = ConfigEntity::getDbNowDate();
                $caibaodetail->created_by = 'schedule';
                if ($caibaodetail->save()) {
                    print('合同明细保存成功,合同ID:' . $contractid . PHP_EOL);
                }
            }

            $manageEntity = ContractManageRepository::getContractManageModelByContractId($contractid);
            $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
            $num = $manageEntity->inc;
            $num < 10 && $num = "0" . $num;
            $incomecode = $contractManage->contract_code . "-SR-" . $num; // 生成收入项编码

            //同步生成应收款
            $income = new ContractRevenueEntity();
            $income->revenue_id = StringHelper::uuid();
            $income->contract_id = $contractid;
            $income->revenue_type = 'a8d08aa9-baad-4279-bbe1-1d05852b9e38';
            $income->amount = $thismonthconsumemoney;
            $income->income_code = $incomecode;
            $income->wait_confirm_amount = $thismonthconsumemoney;
            $income->carryover_begin_time = $thismonthlastday;
            $income->right_begin_time = $lastmonthfirstday;
            $income->right_end_time = $thismonthlastday;
            $income->remark = '釆宝调度生成合同时同步生成应收款!';
            $income->created_on = ConfigEntity::getDbNowDate();
            $now = $income->getAttributes();
            $res = $income->save();
            IncomeItemLogRepository::add(false,$now,$res, IncomeItemLogRepository::OPERATE_ADD);
            if ($res) {
                print('应收款信息同步保存成功,合同ID:' . $contractid . PHP_EOL);
            }
            $manageEntity->save();

            //数据保存成功后,将之前本月的支付信息合同ID同步为此合同ID
            $payinfos = ContractPayinfoEntity::find()->where("product_name='云采购采宝' and pay_time>='" . $lastmonthfirstday . "' and pay_time<='" . $thismonthlastday . "'")->all();
            foreach ($payinfos as $item) {
                $item->contract_id = $contractid;
                if ($item->save()) {
                    print('支付信息合同ID更新成功:' . $contractid . PHP_EOL);
                }
            }

            print('合同保存成功:' . $contractManage->contract_id . PHP_EOL);
        }
    }

    public function actionSyncSupplierGoldOrder()
    {
        $confUrl = \Yii::$app->params['MYCAIGOU_API_URL'];
        $apiUrl = $confUrl . 'get-supplier-gold-order';
        $getdata = CurlHelper::getCurlData($apiUrl, false, false);

        if (empty($getdata)) {
            print('远程接口请求结果异常!' . $apiUrl . PHP_EOL);
            return;
        }
        if (empty($getdata->data)) {
            print('本次查询无数据:' . $apiUrl) . PHP_EOL;
            return;
        }
        //获取待处理订单
        $orderinfos = $getdata->data;
        foreach ($orderinfos as $item) {
            $supplierid = $item->supplier_id;
            if (empty($supplierid)) {
                continue;
            }
            $bgdate = $item->xq_bg_date;
            $signamount = $item->xq_sign_amount;
            $filedownloadpath = $item->xq_file_download_path;
            $remark = empty($item->xq_remark) ? '' : $item->xq_remark;
            if (empty($bgdate)) {
                $bgdate = $item->begin_date;
            }
            $enddate = $item->xq_end_date;
            if (empty($enddate)) {
                $enddate = $item->end_date;
            }
            if (empty($signamount)) {
                $signamount = $item->sign_amount;
                if (empty($signamount)) {
                    $signamount = 0;
                }
            }
            if ($signamount == 0) {
                continue;
            }
            if (empty($filedownloadpath)) {
                $filedownloadpath = $item->file_download_path;
                if (empty($filedownloadpath)) {
                    $filedownloadpath = '';
                }
            }
            if (empty($remark)) {
                $remark = empty($item->remark) ? '' : $item->remark;
                if (empty($remark)) {
                    $remark = '';
                }
            }

            $contract = ContractManageRepository::getContractBySupplierInfo($supplierid, $bgdate, $enddate);
            if ($contract) {
                continue;
            }
            $contractManage = new ContractManageEntity();
            $contractId = StringHelper::uuid();

            $erpuserguid = '';
            $erpuserdepguid = '';
//            if(!empty($item->ycg_signer)) {
//                $erpuser = ErpUserRepository::getErpUserByKeyword($item->ycg_signer, 1);
//                if (!empty($erpuser)) {
//                    $erpuserguid = $erpuser[0]['UserGUID'];
//                    $erpuserdepguid = $erpuser[0]['DepartmentGUID'];
//                }
//            }

            $contractManage->business_type_id = ConstInfo::CONTRACT_BUSSINESS_TYPE_YCGHY;
            $contractManage->contract_code = ContractFlowCodeRepository::getContractCode();   //生成合同编码
            $contractManage->contract_id = $contractId;   //新建合同ID
            $contractManage->supplier_id = $supplierid;     //供应商ID
            $contractManage->supplier_name = $item->company_name;
            $contractManage->customer_name = $item->company_name;
            $contractManage->customer_full_name = $item->company_name;
            $contractManage->sign_date = $bgdate;
            $contractManage->effect_date = $bgdate;
            $contractManage->input_date = ConfigEntity::getDbNowDate();
            $contractManage->sign_people_id = $erpuserguid;
            $contractManage->sign_people_name = $item->ycg_signer;
            $contractManage->sign_people_department_id = $erpuserdepguid;
            $contractManage->sign_amount = $signamount;
            $contractManage->give_work_day = 0;
            $contractManage->develop_work_day = 0;
            $contractManage->implement_work_day = 0;
            $contractManage->contract_property_id = '037b890b-5ae3-11e7-9f96-000c29310f8b';    //云链直销,转换过为性质表的ID
            $contractManage->company_id = 'a3d3a00a-4b29-11e7-af9f-005056a65fd7';  //明源云链,转换为公司ID
            $contractManage->contract_status = 2;
            $contractManage->created_by = 'schedule';
            $contractManage->created_on = ConfigEntity::getDbNowDate();
            $contractManage->modified_on = ConfigEntity::getDbNowDate();
            $contractManage->contract_remark = $remark;

            if ($contractManage->save()) {
                print('金牌会员合同保存成功:' . $contractId . PHP_EOL);
                //保存交付信息
                $payover = new ContractPayoverEntity();
                $payover->contract_payover_id = StringHelper::uuid();
                $payover->contract_id = $contractId;
                $payover->contract_code = $contractManage->contract_code;
                $payover->application_name = '云采购会员';
                $payover->amount = $signamount;
                $payover->authorize_time = $bgdate;
                $payover->begin_time = $bgdate;
                $payover->end_time = $enddate;
                $payover->edit_mode = '2';
                $payover->created_on = ConfigEntity::getDbNowDate();
                $payover->created_by = 'schedule';
                $payover->modified_on = ConfigEntity::getDbNowDate();
                $payover->system_flag = 'sys_add';
                if ($payover->save()) {
                    print('交付信息保存成功:' . $contractId . PHP_EOL);
                }

                //保存收入信息
                $newincome = new ContractRevenueEntity();
                $manageEntity = ContractManageRepository::getContractManageModelByContractId($contractId);
                $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
                $num = $manageEntity->inc;
                $num < 10 && $num = "0" . $num;
                $incomecode = $manageEntity->contract_code . "-SR-" . $num; // 生成收入项编码
                $newincome->revenue_id = StringHelper::uuid();
                $newincome->contract_id = $contractId;
                $newincome->contract_payover_id = $payover->contract_payover_id;
                $newincome->income_code = $incomecode;
                $newincome->revenue_type = ContractService::getBussAccountTypesId($manageEntity->business_type_id, '云采购会员');
                $newincome->amount = $signamount;
                $newincome->carryover_begin_time = $bgdate;
                $newincome->right_begin_time = $bgdate;
                $newincome->right_end_time = $enddate;
                $newincome->wait_confirm_amount = $signamount;
                $newincome->created_on = ConfigEntity::getDbNowDate();
                $newincome->modified_on = ConfigEntity::getDbNowDate();
                $newincome->remark = '云采购会员调度数据时同步生成';
                $now = $newincome->getAttributes();
                $res = $newincome->save();
                IncomeItemLogRepository::add(false,$now,$res,IncomeItemLogRepository::OPERATE_ADD);
                if ($res) {
                    $manageEntity->save();
                    print('应收信息保存成功:' . $contractId . PHP_EOL);
                }

                //保存合同附件信息
                if (!empty($filedownloadpath)) {
                    $doc = new DocumentEntity();
                    $doc->business_id = $contractId;
                    $doc->document_id = StringHelper::uuid();
                    $doc->document_path = $filedownloadpath;
                    $doc->document_ext_name = '合同附件';
                    $doc->document_name = '合同附件';
                    $doc->created_on = ConfigEntity::getDbNowDate();
                    $doc->created_by = 'schedule';
                    if ($doc->save()) {
                        print('合同附件保存成功:' . $contractId . PHP_EOL);
                    }
                }
            }
        }
    }

    /**
     *获取云采购的供应商考察报告数据
     */
    public function actionSyncInvestReport()
    {
        $confUrl = \Yii::$app->params['MYCAIGOU_API_URL'];
        $confImgUrl = \Yii::$app->params['MYCAIGOU_IMG_URL'];
        $apiUrl = $confUrl . 'get-invest-report?supplierid=';
        //查询还没有获取考察报告的合同,循环获取数据
        $sql = 'SELECT m.contract_id,m.contract_code,m.supplier_id,m.sign_amount,m.balance_should_amount,sign_date ' .
            'FROM myscrm_contract_manage m ' .
            'left join myscrm_contract_payover p on m.contract_id=p.contract_id ' .
            'where m.business_type_id=\'f85729eb-54ca-11e7-9f96-000c29310f8b\' AND IFNULL(m.supplier_id,\'\')!=\'\' AND p.contract_id is NULL';
        $result = \Yii::$app->cdb->createCommand($sql)->queryAll();
        foreach ($result as $item) {
            //获取待处理订单
            //附件:https://img4.fdczbstatic.com/netdiskimg/supplier-26/592847088340005e9512a7e4.800x1140.jpg

            $getdata = CurlHelper::getCurlData($apiUrl . $item['supplier_id'], false, false);
            //$getdata = CurlHelper::getCurlData('http://mytest.com:1002/api/index.php?r=/channel/return-model-data', false, false);
            echo $apiUrl . $item['supplier_id'] . PHP_EOL;

            if (empty($getdata)) {
                print('远程接口请求结果异常!' . $apiUrl . PHP_EOL);
                return;
            }
            if (empty($getdata->data)) {
                print('本次查询无数据' . PHP_EOL);
                continue;
            }
            $reportinfos = $getdata->data;
            foreach ($reportinfos as $reportinfo) {
                $payover = ContractPayoverEntity::find()->where("contract_id='" . $item['contract_id'] . "' and foreign_id='" . $reportinfo->uid . "' and system_flag='sys_kcbg'")->one();
                if (empty($payover)) {
                    $payover = new ContractPayoverEntity();
                    $contractpayoverid = StringHelper::uuid();
                    $payover->contract_payover_id = $contractpayoverid;
                    $payover->contract_id = $item['contract_id'];
                    $payover->contract_code = $item['contract_code'];
                    $payover->foreign_id = $reportinfo->uid;
                    $payover->application_name = $reportinfo->company_name . '考察报告';
                    $payover->authorize_time = $reportinfo->investigation_time;
                    $payover->begin_time = $reportinfo->investigation_time;
                    $payover->end_time = $reportinfo->expiration_time;
                    $payover->system_flag = 'sys_kcbg';
                    $payover->created_on = ConfigEntity::getDbNowDate();
                    $payover->created_by = 'schedule';
                    if ($payover->save()) {
                        print('保存成功:' . $payover->contract_payover_id . PHP_EOL);
                    }
                } else {
                    $contractpayoverid = $payover->contract_payover_id;
                }

                $isHaveCarryover = ContractRevenueRepository::isHaveCarryover($item['contract_id']);
                //已结转的不支持重复执行
                if (!$isHaveCarryover) {
                    $newincome = new ContractRevenueEntity();
                    $manageEntity = ContractManageRepository::getContractManageModelByContractId($item['contract_id']);
                    $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
                    $num = $manageEntity->inc;
                    $num < 10 && $num = "0" . $num;
                    $incomecode = $manageEntity->contract_code . "-SR-" . $num; // 生成收入项编码
                    $newincome->revenue_id = StringHelper::uuid();
                    $newincome->contract_id = $item['contract_id'];
                    $newincome->contract_payover_id = $contractpayoverid;
                    $newincome->income_code = $incomecode;
                    $newincome->revenue_type = ContractService::getBussAccountTypesId($manageEntity->business_type_id, '供应商考察报告');
                    //$newincome->amount = $item['sign_amount'];
                    $newincome->amount = $item['balance_should_amount'];//更改为应收款金额2018/5/24
                    $newincome->carryover_begin_time = $item['sign_date'];
                    $newincome->right_begin_time = $reportinfo->investigation_time;
                    $newincome->right_end_time = $reportinfo->investigation_time;
                    $newincome->wait_confirm_amount = $item['sign_amount'];
                    $newincome->created_on = ConfigEntity::getDbNowDate();
                    $newincome->remark = '考察报告调度数据时同步生成';
                    $now = $newincome->getAttributes();
                    $res = $newincome->save();
                    IncomeItemLogRepository::add(false,$now,$res, IncomeItemLogRepository::OPERATE_ADD);
                    $manageEntity->save();
                }

                //保存考察报告文件信息
                $contractfile = new ContractFileEntity();
                $contractfile->contract_file_id = StringHelper::uuid();
                $contractfile->contract_id = $item['contract_id'];
                $contractfile->business_id = $contractpayoverid;
                $contractfile->source_file_id = $reportinfo->file_id;
                $contractfile->source_file_path = $confImgUrl . $reportinfo->use_age . "/" . $reportinfo->file_id . '.800x1140.jpg';
                $contractfile->files_status = 0;
                $contractfile->created_on = ConfigEntity::getDbNowDate();
                $contractfile->created_by = 'schedule';
                if ($contractfile->save()) {
                    print('考察报告文件保存成功:' . $contractpayoverid) . PHP_EOL;
                }
            }
        }
    }

    /**
     * 上传图片
     */
    public function actionUploadFiles()
    {
        $contractfiles = ContractFileEntity::find()->where('files_status=0')->all();
        foreach ($contractfiles as $item) {
            $filefullpath = $item->source_file_path;
            $file = fopen($filefullpath, 'r');
            $fileext = pathinfo($filefullpath, PATHINFO_EXTENSION);
//            $filetype = mime_content_type($file);
            $filetype = 'image/' . $fileext;
            $newdocname = $item->source_file_id . "." . $fileext;
            $uploadpath = dirname(__FILE__) . "/upload/";
            if (!file_exists($uploadpath)) {
                mkdir($uploadpath);
            }
            $uploadfilename = $uploadpath . $newdocname;
            if (!$file) {
                echo 'Remote picture open fail!' . PHP_EOL;
                return;
            }
            $newfile = fopen($uploadfilename, 'w');
            while (!feof($file)) {
                if (!fwrite($newfile, fread($file, 1024 * 8), 1024 * 8)) {
                    echo 'Write file error!' . PHP_EOL;
                }
            }
            fclose($file);
            fclose($newfile);

            echo 'Download file over!' . $newdocname . PHP_EOL;

            $httpfile = null;
            $httpfile["name"] = $newdocname;
            $httpfile["size"] = filesize($uploadfilename);
            $httpfile["type"] = $filetype;
            $httpfile["tmp_name"] = $uploadfilename;
            try {
                $uploader = $this->getImageUploader($httpfile);
                $picurl = $uploader->upload();

                //保存文档信息到数据库
                $doc = new DocumentEntity();
                $doc->document_id = StringHelper::uuid();
                $doc->document_name = $newdocname;
                $doc->document_ext_name = $fileext;
                $doc->document_path = $picurl;
                $doc->business_id = $item->contract_id;
                $doc->created_on = ConfigEntity::getDbNowDate();
                $doc->created_by = 'schedule';
                if ($doc->save()) {
                    echo '图片在文档表保存成功:' . $doc->document_id . PHP_EOL;
                }
                $item->files_status = 1;
            } catch (Exception $ex) {
                echo $ex->getMessage() . PHP_EOL;
                $item->files_status = 2;
                return;
            }
            $item->save();
            echo 'pload over! File path:' . $picurl . PHP_EOL;


//        //本地文件使用完成后删除
//        chmod($newfilename,0755);
//        if(!file_exists($newfilename)){
//            echo 'local file no exists!'.PHP_EOL;
//        }
//        if(unlink($newfilename)){
//            echo 'local file delete success!'.PHP_EOL;
//        }
        }
    }

    /**
     * 同步移动工程协同订单及支付信息
     */
    public function actionSyncYdgcOrderInfo()
    {
        $orderconfig = \Yii::$app->params['Ydgcxt_PAAS_API'];
        //$apiUrl = $this->getUrl($confUrl,'query','start_time','end_time');
        //$getdata = CurlHelper::getCurlData($apiUrl, false, false);
        $paramArr = $this->getParamsArr('start_time', 'end_time');
        $paramArr2 = ['page_size' => 500, 'page' => 1];
        $paramArr = array_merge($paramArr, $paramArr2);
        $params = $this->getParams('start_time', 'end_time');
        $params .= '&page_size=500&page=1';
        $getdata = JWTHelper::sendRequestToOderApi($paramArr, '/market/indent/query?' . $params, $orderconfig, 'get');
        print('参数:' . $params . PHP_EOL);

        if (empty($getdata)) {
            print('远程接口请求结果异常!' . PHP_EOL);
            return;
        }
        if (empty($getdata['data']['items'])) {
            print('本次查询无数据:') . PHP_EOL;
            return;
        }
        //获取待处理订单
        $orderinfos = $getdata['data']['items'];

        print_r($orderinfos);

        foreach ($orderinfos as $item) {
            $pay_customer = trim($item['pay_customer']);
            if ($item['contract_amount'] < 10) {
                print('订单Code为:' . $item['order_code'] . '的记录金额小于10,为测试数据,不生成合同.' . PHP_EOL);
                continue;
            }
            $contractManage = ContractManageEntity::find()->where(['orderid' => $item['order_code']])->one();    //判断订单号是否已存在,存在则执行下次循环
            if (!empty($contractManage)) {
                print('订单Code为:' . $item['order_code'] . '的合同已存在.' . PHP_EOL);
                continue;
            }

            $producename = $item['seller_name'];   //移动工程协同saas
            $contractId = StringHelper::uuid(); //提前存储合同ID,关联信息都使用此ID
            $nowtime = ConfigEntity::getDbNowDate();

            //保存开发商基本信息
            $developer = new ContractDeveloperEntity();
            $developer->contract_id = $contractId;
            $developer->customer_name = $pay_customer;
            $developer->customer_full_name = $pay_customer;
            $developer->developer_contract_id = '';     //对应开发商合同ID
            if ($developer->save()) {
                print('开发商信息保存成功' . $developer->contract_id . PHP_EOL);
            }

            //保存支付信息
            $payinfo = new ContractPayinfoEntity();
            $payinfo->payinfo_id = StringHelper::uuid();
            $payinfo->contract_id = $contractId;
            $payinfo->pay_amount = $item['contract_amount'];
            $payinfo->pay_time = $item['order_time'];
            $payinfo->user_name = $item['pay_username'];
            $payinfo->company_name = $pay_customer;
            $payinfo->pay_order_id = $item['pay_id'];
            $payinfo->order_code = $item['order_code'];
            $payinfo->pay_way = $item['pay_mode'];
            $payinfo->product_name = $item['product_name'];
            $payinfo->created_by = 'schedule';
            $payinfo->created_on = $nowtime;
            if ($payinfo->save()) {
                print('支付信息保存成功:' . $payinfo->contract_id . PHP_EOL);
            }

            //保存产品(充值卡)信息
            $contractProduct = new ContractProductEntity();
            $contractProduct->product_id = StringHelper::uuid();
            $contractProduct->contract_id = $contractId;
            $contractProduct->pname = $item['card_name'];
            $contractProduct->pcode = $item['card_code'];
            $contractProduct->spec = $item['card_specs'];
            $contractProduct->quantity = $item['card_quantity'];
            $contractProduct->unitprice = $item['card_price'];
            $contractProduct->totalamount = $item['card_paid'];
            if ($contractProduct->save()) {
                print('充值卡信息保存成功:' . $contractProduct->contract_id . PHP_EOL);
            }

            //保存合同主表
            $contractManage = new ContractManageEntity();
            $linkcontractid = $this->getLinkContractId($item['pay_customer_code']);

            //如果没找到关联合同，则判断是否为指定格式，如果是则指定关联合同
            if($linkcontractid == '' && $pay_customer == '深圳市中洲投资控股股份有限公司'){
                $linkcontractid = '39e3a96c-033d-6aec-08f5-ad9ba151913e';
            }
            $contractManage->contract_id = $contractId;   //新建合同ID
            $contractManage->business_type_id = ConstInfo::CONTRACT_BUSSINESS_TYPE_YDGCXT;
            $contractManage->contract_code = ContractFlowCodeRepository::getContractCode();   //生成合同编码
            $contractManage->link_customer_code = $item['pay_customer_code'];
            $contractManage->link_contract_id = $linkcontractid;
            $contractManage->customer_name = $pay_customer;
            $contractManage->customer_full_name = $pay_customer;
            $contractManage->sign_amount = $item['contract_amount'];
            $contractManage->sign_date = $item['order_time'];


            $contractManage->contract_property_id = 'c3402517-54d8-11e7-9f96-000c29310f8b';//移动工程协同的业务改字段，合同性质根据签约人所在公司，改为云链签约-联营、云链签约-直属
            $balancerate = 0.5;
            $linkareaname = '';
            if ($contractManage->customer_name == "碧桂园房地产") {
                $balancerate = 0.25;
            }
            if (!empty($linkcontractid)) {
                $linkmodel = ContractManageRepository::getContractManageModelByContractId($linkcontractid);
                $linkareaname = ErpBusinessUnitRepository::getBunameByBuguid($linkmodel->area_id);
                if ($linkareaname == '北京分公司' || $linkareaname == '上海分公司' || $linkareaname == '广州分公司' || $linkareaname == '深圳分公司') {
                    $contractManage->contract_property_id = 'c33eda1c-54d8-11e7-9f96-000c29310f8b';    //云链签约-直属,转换过为性质表的ID
                }

                if ($linkareaname == '中山公司' || $linkareaname == '海南公司') {
                    $balancerate = 0.25;
                }
            }

            $contractManage->balance_rate = $balancerate;
            $contractManage->balance_should_amount = $balancerate * intval($contractManage->sign_amount);
            $contractManage->balance_amount = $contractManage->balance_should_amount;
            $contractManage->back_amount = $contractManage->sign_amount - $contractManage->balance_should_amount;

            $contractManage->effect_date = $item['order_time'];
            $contractManage->input_date = $item['order_time'];
            $contractManage->orderid = $item['order_code'];
            $contractManage->give_work_day = 0;
            $contractManage->develop_work_day = 0;
            $contractManage->implement_work_day = 0;
            $contractManage->contract_status = 2;
            //$contractManage ->contract_property_id = '037b890b-5ae3-11e7-9f96-000c29310f8b';

            $contractManage->supplier_name = '移动工程协同-' . $linkareaname . '-' . $pay_customer . '(供应商)';
            $contractManage->company_id = 'a3d3a00a-4b29-11e7-af9f-005056a65fd7';  //明源云链,转换为公司ID
            $contractManage->created_by = 'schedule';
            $contractManage->created_on = $nowtime;
            $contractManage->contract_remark = $producename . ' 订单生成合同';

            if ($contractManage->save()) {
                print('保存成功:' . $contractManage->contract_id . PHP_EOL);
            }
        }
        return '';
    }

    private function getLinkContractId($cstcode)
    {
        $relationifno = ContractTenantRelationEntity::find()->where(['tenant_id' => $cstcode])->one();
        return empty($relationifno) ? '' : $relationifno->contract_id;
    }

    /**
     * 获取移动工程协同的交付信息
     */
    public function actionSyncYdgcPayoverInfo()
    {
        $ydgcconfig = \Yii::$app->params['Ydgcxt_PAAS_API'];

//        $contracts = ContractManageEntity::find()
//            ->where("IFNULL(orderid,'')!='' AND business_type_id='9a96f3dc-54ca-11e7-9f96-000c29310f8b'")
//            ->all();

        $conn = ContractManageEntity::getDb();
        $sql = "SELECT m.contract_code,m.contract_id,m.customer_name,m.sign_amount,m.link_contract_id,m.orderid,IFNULL(p.cardcount,0) cardcount,IFNULL(po.cardcount,0) havegetcount
                FROM myscrm_contract_manage m
                inner join (SELECT contract_id,SUM(spec) cardcount FROM myscrm_contract_product group by contract_id) p on m.contract_id=p.contract_id
                left join (SELECT contract_id,SUM(authorization_numeric) cardcount FROM myscrm_contract_payover WHERE system_flag='dzh_gcxt' group by contract_id) po on po.contract_id=m.contract_id
                where IFNULL(m.orderid,'')!='' AND m.business_type_id='9a96f3dc-54ca-11e7-9f96-000c29310f8b'
                AND (IFNULL(po.cardcount,0)<IFNULL(p.cardcount,0))";
        $contracts = $conn->createCommand($sql)->queryAll();

        foreach ($contracts as $contract) {
            $ordercode = $contract['orderid'];
            $contractid = $contract['contract_id'];
            $customname = $contract['customer_name'];
            $signamount = $contract['sign_amount'];
            $linkcontractid = $contract['link_contract_id'];
//            $apiUrl = $ydgcconfig.'/market/card/'.$ordercode;
            //https://api-test.mypaas.com.cn/market/card/used-list?order_code='.$ordercode;
//            $getdata = CurlHelper::getCurlData($apiUrl, false, false);

            $getdata = JWTHelper::sendRequestToOderApi(['order_code' => $ordercode], '/market/card/used-list?order_code=' . $ordercode, $ydgcconfig, 'get');
            print('参数:' . $ordercode . PHP_EOL);

            if (empty($getdata)) {
                print('远程接口请求结果异常!' . PHP_EOL);
                return;
            }
            if (empty($getdata['data'])) {
                print('本次查询无数据:') . PHP_EOL;
                continue;
            }
            $payovers = ContractPayoverEntity::find()->where("contract_id='" . $contractid . "' and system_flag='dzh_gcxt'")->all();
            //获取待处理订单
            $urldatas = $getdata['data'];
            //生成交付数据
            foreach ($urldatas as $urldata) {
                $isExists = false;
                foreach ($payovers as $payover) {
                    //充值卡编号作为标记,确认是否已经拉取过
                    if ($urldata['card_num'] == $payover['foreign_id']) {
                        $isExists = true;
                    }
                }
                //不存在则新增
                if (!$isExists) {
                    $nowtime = ConfigEntity::getDbNowDate();
                    $endtime = null;
                    if (!empty($urldata['card_specs']) && !empty($urldata['charge_time'])) {
                        $endtime = date('Y-m-d H:i:s', strtotime("+" . $urldata['card_specs'] . " months", strtotime($urldata['charge_time'])));
                    }
                    $newpayover = new ContractPayoverEntity();
                    $newpayover->contract_payover_id = StringHelper::uuid();
                    $newpayover->contract_id = $contractid;
                    $newpayover->contract_code = $contract['contract_code'];
                    $newpayover->foreign_id = $urldata['card_num'];
                    $newpayover->application_id = '0df6297e-e421-4a35-aa34-497c59a529ba';
                    $newpayover->application_name = '移动工程协同租用服务（供应商）';
                    $newpayover->authorization_numeric = $urldata['card_specs'];
                    $newpayover->system_flag = 'dzh_gcxt';
                    $newpayover->user_name = $urldata['charge_object'];
                    $newpayover->authorize_time = $urldata['charge_time'];
                    $newpayover->begin_time = $urldata['charge_time'];
                    $newpayover->end_time = $endtime;
                    $newpayover->amount = $signamount;

                    $balancerate = 0.5;
                    if ($customname == "碧桂园房地产") {
                        $balancerate = 0.25;
                    }
                    if (!empty($linkcontractid)) {
                        $linkmodel = ContractManageRepository::getContractManageModelByContractId($linkcontractid);
                        $linkareaname = ErpBusinessUnitRepository::getBunameByBuguid($linkmodel->area_id);
                        if ($linkareaname == '中山公司' || $linkareaname == '海南公司') {
                            $balancerate = 0.25;
                        }
                    }
                    $newpayover->balance_rate = $balancerate;;
                    $newpayover->balance_amount = $balancerate * $signamount;
                    $newpayover->edit_mode = 0;
                    $newpayover->created_on = $nowtime;
                    $newpayover->created_by = 'schedule';
                    if (!$newpayover->save()) {
                        print('交付信息保存失败!' . PHP_EOL);
                    } else {
                        print('交付信息保存成功!' . $newpayover->contract_payover_id . PHP_EOL);
                        //交付信息保存成功后再生成收入信息
                        $manageEntity = ContractManageRepository::getContractManageModelByContractId($contractid);
                        $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
                        $num = $manageEntity->inc;
                        $num < 10 && $num = "0" . $num;
                        $incomecode = $manageEntity->contract_code . "-SR-" . $num; // 生成收入项编码
                        $newincome = new ContractRevenueEntity();
                        $newincome->revenue_id = StringHelper::uuid();
                        $newincome->contract_id = $contractid;
                        $newincome->contract_payover_id = $newpayover->contract_payover_id;
                        $newincome->income_code = $incomecode;
                        $newincome->revenue_type = '8fd17068-5eb4-4588-816d-8376bba2caf7';
                        $newincome->amount = $newpayover->balance_amount;
                        $newincome->carryover_begin_time = $urldata['charge_time'];
                        $newincome->right_begin_time = $urldata['charge_time'];
                        $newincome->right_end_time = $endtime;
                        $newincome->wait_confirm_amount = $newpayover->balance_amount;
                        $newincome->created_on = ConfigEntity::getDbNowDate();
                        $newincome->remark = '结算与返款界面保存数据时同步生成';
                        $now = $newincome->getAttributes();
                        $res = $newincome->save();
                        IncomeItemLogRepository::add(false,$now,$res, IncomeItemLogRepository::OPERATE_ADD);
                        if ($manageEntity->save()) {
                            print('收入信息保存成功!' . $newincome->revenue_id . PHP_EOL);
                        }

                        $re = ContractService::generalShipment($contractid);
                        if ($re) {
                            print('出库信息成功产生!' . $contractid . PHP_EOL);
                        } else {
                            print('出库信息产生出错!' . $contractid . PHP_EOL);
                        }
//
//                        //更新合同相关信息
//                        $amount = $this->getContractBalanceAmount($contractid);
//                        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractid);
//                        $contractModel->balance_amount = $amount;
//                        $contractModel->balance_should_amount = $amount;
//                        $contractModel->back_amount = $contractModel['sign_amount'] - $amount;
//                        if($contractModel->save()){
//                            $re = ContractService::generalShipment($contractid);
//                            if($re){
//                                print('合同信息更新成功后,出库信息成功产生!'.$contractid.PHP_EOL);
//                            }else{
//                                print('合同信息更新成功后,出库信息产生出错!'.$contractid.PHP_EOL);
//                            }
//                        };

                    }
                }
            }
        }
    }

    private function getContractBalanceAmount($contractid)
    {
        $payovers = ContractPayoverEntity::find()->where(['contract_id' => $contractid])->all();
        $amount = 0;
        foreach ($payovers as $po) {
            $amount += $po['balance_amount'];
        }
        return $amount;
    }

    /**
     * 通过主数据产品信息
     */
    public function actionSyncProductInfo()
    {
        ini_set('max_execution_time', 1200);
        ini_set('default_socket_timeout', 600);

        $wsdl = \Yii::$app->params['Zsj_API_URL'];

        $soap = new \SoapClient($wsdl);
        $obj = $soap->GetProduct();
        $data = $obj->GetProductResult;

        $dataArr = json_decode($data);
        print_r($dataArr);
        if (empty($dataArr)) {
            print('接口未获取到数据' . PHP_EOL);
            return;
        }
        try {

            foreach ($dataArr as $item) {
                if ($item->ProductCategoriesName != "云链") {
                    continue;
                }
                //保存产品信息
                $applicationid = $item->ProductID;
                $incometypeid = $item->IncomeTypeID;
                $incometypename = $item->IncomeTypeName;
                $FinancialInComeType = empty($item->FinancialInComeType) ? '' : $item->FinancialInComeType;
                $nowtime = ConfigEntity::getDbNowDate();
                $productinfo = ApplicationInfoEntity::find()->where(['application_id' => $applicationid])->one();
                if (empty($productinfo)) {
                    $productinfo = new ApplicationInfoEntity();
                    $productinfo->created_on = $nowtime;
                    $productinfo->created_by = 'schedule';
                }
                $productinfo->application_id = $applicationid;
                $productinfo->application_name = $item->ProductName;
                $productinfo->ProductCategoriesID = $item->ProductCategoriesID;
                $productinfo->ProductCategoriesName = $item->ProductCategoriesName;
                $productinfo->ProductSmallCategoriesID = $item->ProductSmallCategoriesID;
                $productinfo->ProductSmallCategoriesName = $item->ProductSmallCategoriesName;
                $productinfo->IncomeTypeID = $incometypeid;
                $productinfo->RegisterName = $item->RegisterName;
                $productinfo->BenchmarkPrice = $item->BenchmarkPrice;
                $productinfo->StandardPrice = $item->StandardPrice;
                $productinfo->LicensingStandards = $item->LicensingStandards;
                $productinfo->StandardConfiguration = $item->StandardConfiguration;
                $productinfo->IsOffShelf = $item->IsOffShelf;
                $productinfo->IsVaild = $item->IsVaild;
                $productinfo->RoyaltyMode = $item->RoyaltyMode;
                $productinfo->SettlementBUName = $item->SettlementBUName;
                $productinfo->BusinessTypeID = $item->BusinessTypeID;
                $productinfo->BusinessTypeID = $item->BusinessTypeID;
                $productinfo->BusinessTypeName = $item->BusinessTypeName;
                $productinfo->modified_on = $nowtime;
                $productinfo->modified_by = 'schedule';

                if ($productinfo->save()) {
                    print('产品信息保存成功:' . $applicationid . PHP_EOL);
                    //收入项信息,判断并保存 myscrm_buss_account_types
                    if (empty($incometypeid)) {
                        continue;
                    }
                    $newacctype = BussAccountTypesEntity::find()->where(['type_id' => $incometypeid])->one();
                    if (empty($newacctype)) {
                        $newacctype = new BussAccountTypesEntity();
                        $newacctype->type_id = $incometypeid;
                        $newacctype->created_on = $nowtime;
                        $newacctype->created_by = 'schedule';
                    }
                    $newacctype->type_name = $incometypename;
                    $newacctype->finance_type_name = $FinancialInComeType;
                    if ($incometypename == '云链租用服务' || $incometypename == '云链平台') {
                        $newacctype->confirm_type = 1;
                    }
                    $newacctype->modified_on = $nowtime;
                    $newacctype->modified_by = 'schedule';
                    if ($newacctype->save()) {
                        print('收入项信息保存成功:' . $incometypeid . PHP_EOL);
                    }
                }
            }
        } catch (Exception $ex) {
            print('接口处理异常:' . (string)$ex . PHP_EOL);
        }
        return '';
    }

    /**
     * 读取税控系统发票数据保存
     * @return string
     */
    public function actionSyncSkInvoice()
    {
        ini_set('max_execution_time', 1200);
        ini_set('default_socket_timeout', 600);

        $wsdl = \Yii::$app->params['Sk_API_URL'];
        print($wsdl . PHP_EOL);
        $msg = '';

        //轮询支付信息将未拿到发票的支付信息再次获取
        $soap = new \SoapClient($wsdl);

        $payinfo = new ContractPayinfoEntity();
        $rows = $payinfo->find()->where(['isGetInvoice' => '0', 'isNeedInvoice' => '1'])->all();

        foreach ($rows as $item) {
            $ordercode = $item->order_code;
            print('编码:' . $ordercode . PHP_EOL);
            if (empty($ordercode)) {
                continue;
            }
            $param = array('orderCode' => $ordercode);

            $obj = $soap->GetInvoiceInfo($param);
            $dataArr = $obj->GetInvoiceInfoResult;

            $dataArr = json_decode($dataArr);
            $data = $dataArr->Data;
            if (empty($data) || empty($data[0])) {
                print('订单编码:' . $ordercode . '查询不到发票信息!' . PHP_EOL);
                continue;
            }
            $data = $dataArr->Data[0];

            print_r($data);

            $invoice = InvoiceEntity::find()->where(['invoice_code' => $data->Code, 'invoice_no' => $data->Number])->one();
            if (!empty($invoice)) {
                print('商城订单编码:' . $ordercode . '的发票已获取!' . PHP_EOL);
                continue;
            }
            $invoiceid = StringHelper::uuid();
            $nowtime = ConfigEntity::getDbNowDate();
            $invoice = new InvoiceEntity();
            $invoice->invoice_id = $invoiceid;
            $invoice->contract_id = $item->contract_id;
            $invoice->invoice_type = $data->InvoiceType == '增值税专用发票' ? 1 : 0;           //发票类型,转换为数字
            $invoice->invoice_code = $data->Code;
            $invoice->invoice_no = $data->Number;
            $invoice->customer_name = $data->BuyerCompanyName;
            $invoice->invoice_category = $data->InvoiceCategory == '服务票' ? 1 : 0;   //发票类别,转换为数字
            $invoice->invoice_date = $data->KPDate;
            $invoice->invoice_amount = $data->AmountWithTax;
            $invoice->invoice_company_id = $data->SellerCompanyName == '深圳市明源云空间电子商务有限公司' ? '2d56a9a5-5a12-11e7-bf1f-7cd30abdab3e' : $data->SellerCompanyName == '深圳市明源云链电子商务有限公司' ? 'f9ecae29-5a11-11e7-bf1f-7cd30abdab3e' : '';      //开票公司,需求确定后调整
            $invoice->created_on = $nowtime;
            $invoice->created_by = 'schedule';
            $invoice->remark = $data->InvoiceContent;
            if (!$invoice->save()) {
                print('发票信息保存成功,编码:' . $data->Code . PHP_EOL);
            }

            //发票内容,转换为摘要,保存摘要信息
            if (!empty($data->InvoiceContent)) {
                $invoiceSummary = new InvoiceSummaryEntity();
                $invoiceSummary->summary_id = StringHelper::uuid();
                $invoiceSummary->invoice_id = $invoiceid;
                $invoiceSummary->summary_type = $data->InvoiceContent;
                $invoiceSummary->summary_amount = $data->AmountWithTax;
                $invoiceSummary->created_by = 'schedule';
                $invoiceSummary->created_on = $nowtime;
                if (!$invoiceSummary->save()) {
                    print('发票摘要保存成功,编码:' . $ordercode . PHP_EOL);
                }
            }

            //都保存成功后更新支付信息的获取发票状态
            $item->isGetInvoice = 1;
            $item->modified_on = ConfigEntity::getDbNowDate();
            $item->save();
        }
        echo '';
    }

    /**
     * 返回完整的URl
     * @param $endtime  查询截止时间
     * @param $mins     查找截止时间之前多少分钟的数据
     * @return string
     */
    private function getUrl($myUrl, $funname, $bgtimename, $endtimename, $endtime = null, $mins = '43200')
    {
        $myUrl = $myUrl . $funname;
        $timestamp = ConfigEntity::getDbNowTimestamp();
        if (empty($endtime)) {
            $endtime = date_create(date('Y-m-d H:i:s', $timestamp));
        } else {
            $endtime = date_create($endtime);
        }
        $endtimestr = str_replace(' ', '%20', $this->ConvertToString($endtime));
        $bgtime = date_sub($endtime, date_interval_create_from_date_string($mins . ' min'));
        $bgtimestr = str_replace(' ', '%20', $this->ConvertToString($bgtime));
        $myUrl = $myUrl . '?bgtime=' . $bgtimestr . '&endtime=' . $endtimestr;
        //指定时间获取数据
        //$myUrl = $myUrl.'?'.$bgtimename.'=2017-09-01%2000:00:00&'.$endtimename.'=2017-09-03%2000:00:00';
        echo '请求地址:' . $myUrl . PHP_EOL;
        return $myUrl;
    }

    private function getParamsArr($bgtimename, $endtimename, $endtime = null, $mins = '43200')
    {
        $timestamp = ConfigEntity::getDbNowTimestamp();
        if (empty($endtime)) {
            $endtime = date_create(date('Y-m-d H:i:s', $timestamp));
        } else {
            $endtime = date_create($endtime);
        }
        $endtimestr = str_replace(' ', '%20', $this->ConvertToString($endtime));
        $bgtime = date_sub($endtime, date_interval_create_from_date_string($mins . ' min'));
        $bgtimestr = str_replace(' ', '%20', $this->ConvertToString($bgtime));
        //指定开始时间
        //$bgtimestr = '2017-09-01%2000:00:00';
        $myParamsArr = [
            $bgtimename => $bgtimestr,
            $endtimename => $endtimestr
        ];
        return $myParamsArr;
    }

    private function getParams($bgtimename, $endtimename, $endtime = null, $mins = '43200')
    {
        $timestamp = ConfigEntity::getDbNowTimestamp();
        if (empty($endtime)) {
            $endtime = date_create(date('Y-m-d H:i:s', $timestamp));
        } else {
            $endtime = date_create($endtime);
        }
        $endtimestr = str_replace(' ', '%20', $this->ConvertToString($endtime));
        $bgtime = date_sub($endtime, date_interval_create_from_date_string($mins . ' min'));
        $bgtimestr = str_replace(' ', '%20', $this->ConvertToString($bgtime));
        $myParam = (empty($bgtimename) ? 'bgtime=' : $bgtimename . '=') . $bgtimestr . '&' . (empty($endtimename) ? '&endtime=' : $endtimename . '=') . $endtimestr;
        //按照指定时间段获取
        //$myParam = (empty($bgtimename)?'bgtime=':$bgtimename).'=2017-09-01%2000:00:00&'.(empty($endtimename)?'&endtime=':$endtimename).$endtimestr;

        return $myParam;
    }

    /**
     * 时间转换成字符串
     */
    public static function ConvertToString($date, $format = 'Y-m-d H:i:s')
    {
        $returnStr = "";
        try {
            if (!empty($date)) {
                if (is_string($date)) {
                    $dateTime = new DateTime($date);
                    $returnStr = date_format($dateTime, $format);
                } else {
                    $returnStr = date_format($date, $format);
                }
            }
        } catch (Exception $ex) {

        }
        return $returnStr;
    }

    /**
     * 根据配置区域不同的图片uploader对象
     * @param type $httpFile
     * @return \common\support\CFileUploader
     */
    private function getImageUploader($httpFile)
    {
        $type = "file";
        $rootPath = "/upfiles";
        if (isset(\Yii::$app->params["uploader"]) && isset(\Yii::$app->params["uploader"]["type"])) {
            $type = \Yii::$app->params["uploader"]["type"];
            $rootPath = \Yii::$app->params["uploader"]["rootPath"];
        }
        $uploader = null;
        $imageSize = 1024 * 1024 * 10; //图片大小限制为1M
        $contentType = [
            "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/jpg"
        ];
        if ($type == 'oss') {
            $uploader = new OSSUploader($imageSize, $contentType, $httpFile, $rootPath);
        }
        return $uploader;
    }

    //向利润系统同步数据
    public function actionSyncDataToProfit()
    {
        $t1 = microtime(true);
        $dbname1 = 'contract_yl';
        $conn1 = ConfigEntity::getDb();   //我们自己的生产环境
        $dbname2 = 'contract_yl';
        $conn2 = ConfigEntity::getDb2();  //需要同步的,对方的库
        $sqlGetInfo = "SELECT
                        TABLE_NAME tbname,
                        GROUP_CONCAT(COLUMN_NAME) columnnames,
                        GROUP_CONCAT(DATA_TYPE) datatypes,
                        GROUP_CONCAT(CASE WHEN COLUMN_KEY='PRI' THEN COLUMN_NAME END) prikey,
                        GROUP_CONCAT(CASE WHEN COLUMN_NAME='modified_on' THEN COLUMN_NAME END) flagfield
                        FROM INFORMATION_SCHEMA.Columns
                        WHERE TABLE_SCHEMA='" . $dbname2 . "' AND TABLE_NAME in (
                        'myscrm_application_info','myscrm_application_balance_rate','myscrm_buss_account_types','myscrm_erp_user',
                        'myscrm_contract_manage','myscrm_contract_application','myscrm_contract_account_company','myscrm_erp_business_unit',
                        'myscrm_contract_company','myscrm_contract_payinfo','myscrm_contract_payment','myscrm_contract_product',
                        'myscrm_contract_payover','myscrm_contr∂act_property','myscrm_contract_receivable','myscrm_contract_revenue',
                        'myscrm_contract_revenue_carryover','myscrm_contract_shipment','myscrm_contract_property','myscrm_contract_category',
                        'myscrm_invoice','myscrm_invoice_business_unit','myscrm_invoice_payment','myscrm_invoice_receivable',
                        'myscrm_invoice_summary','myscrm_receivable_item','myscrm_contract_big_category','myscrm_contract_littler_category',
                        'myscrm_contract','myscrm_organization','myscrm_money_category_item','myscrm_application_bu_rate','myscrm_contract_business_type'
                        ) GROUP BY TABLE_NAME";

        $dataTbInfo = $conn2->createCommand($sqlGetInfo)->queryAll();

        $strInsertAll = '';
        $strUpdateAll = '';
        $strDeleteAll = '';

        //遍历所有表
        foreach ($dataTbInfo as $item) {
            $tbname = $item['tbname'];
            $prikey = $item['prikey'];

            $columnnames = '';
            $flagfield = $item['flagfield'];
            if (empty($prikey)) {
                echo '表:' . $tbname . '没有主键,无法同步!' . PHP_EOL;
                continue;
            }

            //查出表的字段信息
            $sqlTbField = "SELECT COLUMN_NAME,DATA_TYPE
                            FROM INFORMATION_SCHEMA.Columns
                            WHERE TABLE_SCHEMA='" . $dbname2 . "' AND TABLE_NAME = '" . $tbname . "'";
            $tbfieldinfo = $conn2->createCommand($sqlTbField)->queryAll();

            foreach ($tbfieldinfo as $field) {
                if ($columnnames == '') {
                    $columnnames .= $field['COLUMN_NAME'];
                } else {
                    $columnnames .= ',' . $field['COLUMN_NAME'];
                }
            }

            $keyflagcolumn = $prikey;
            if (!empty($flagfield)) {
                $keyflagcolumn .= ',' . $flagfield;
            }

            //查询两个库数据,然后对比
            $sqlSelect = 'SELECT ' . $keyflagcolumn . ' FROM ' . $tbname;

            $selectData1 = $conn1->createCommand($sqlSelect)->queryAll();
            $selectData2 = $conn2->createCommand($sqlSelect)->queryAll();

            //处理新增和修改
            foreach ($selectData1 as $select1) {
                $prikeyvalue = $select1[$prikey];
                $flagfieldvalue = empty($flagfield) ? '' : $select1[$flagfield];
                $isinsert = true;
                $isupdate = false;
                $values = '';
                foreach ($selectData2 as $select2) {
                    if ($prikeyvalue == $select2[$prikey]) {
                        $isinsert = false;
                        if (!empty($flagfieldvalue) && $flagfieldvalue != $select2[$flagfield]) {
                            $isupdate = true;
                        }
                    }
                }
                //判断出新增还是修改,然后才取出对应数据的所有字段,节约内存
                if ($isinsert || $isupdate) {
                    $rowsql = "select " . $columnnames . " from " . $tbname . " where " . $prikey . "='" . $prikeyvalue . "'";
                    $rowData = $conn1->createCommand($rowsql)->queryOne();
                }

                if ($isinsert) {
                    foreach ($tbfieldinfo as $col) {
                        $fieldType = $col['DATA_TYPE'];
                        $fieldValue = $rowData[$col['COLUMN_NAME']];
                        if ($fieldType == 'tinyint' || $fieldType == 'decimal' || $fieldType == 'int' || $fieldType == 'float') {
                            if (empty($fieldValue)) {
                                $fieldValue = '0';
                            }
                        } elseif ($fieldType == 'datetime' || $fieldType == 'timestamp' || $fieldType == 'date' || $fieldType == 'time') {
                            if (empty($fieldValue)) {
                                $fieldValue = 'NULL';
                            } else {
                                $fieldValue = "'" . $fieldValue . "'";
                            }
                        } else {
                            $fieldValue = "'" . $fieldValue . "'";
                        }

                        if ($values == '') {
                            $values = $fieldValue;
                        } else {
                            $values .= "," . $fieldValue;
                        }
                    }
                    $strInsertAll .= 'INSERT ' . $tbname . '(' . $columnnames . ') VALUES(' . $values . ');' . PHP_EOL;
                }
                if ($isupdate) {
                    foreach ($tbfieldinfo as $col) {
                        $fieldType = $col['DATA_TYPE'];
                        $fieldValue = $rowData[$col['COLUMN_NAME']];
                        if ($fieldType == 'tinyint' || $fieldType == 'decimal' || $fieldType == 'int' || $fieldType == 'float') {
                            if (empty($fieldValue)) {
                                $fieldValue = '0';
                            }
                        } elseif ($fieldType == 'datetime' || $fieldType == 'timestamp' || $fieldType == 'date' || $fieldType == 'time') {
                            if (empty($fieldValue)) {
                                $fieldValue = 'NULL';
                            } else {
                                $fieldValue = "'" . $fieldValue . "'";
                            }
                        } else {
                            $fieldValue = "'" . $fieldValue . "'";
                        }

                        if ($col != $prikey) {
                            if ($values == '') {
                                $values .= $col['COLUMN_NAME'] . '=' . $fieldValue;
                            } else {
                                $values .= ',' . $col['COLUMN_NAME'] . '=' . $fieldValue;
                            }
                        }
                    }
                    $strUpdateAll .= "UPDATE " . $tbname . " SET " . $values . " WHERE " . $prikey . "='" . $prikeyvalue . "';" . PHP_EOL;
                }
            }

            //处理删除
            foreach ($selectData2 as $select2) {
                $prikeyvalue = $select2[$prikey];
                $isdelete = true;
                foreach ($selectData1 as $select1) {
                    if ($prikeyvalue == $select1[$prikey]) {
                        $isdelete = false;
                    }
                }
                if ($isdelete) {
                    $strDeleteAll .= "DELETE FROM " . $tbname . " WHERE " . $prikey . "='" . $prikeyvalue . "';" . PHP_EOL;
                }
            }
            unset($selectData1);
            unset($selectData2);
        }

        //echo '执行表:'.$tbname.'执行同步:'.PHP_EOL;
        echo '新增数据:' . PHP_EOL . $strInsertAll . PHP_EOL;
        echo '修改数据:' . PHP_EOL . $strUpdateAll . PHP_EOL;
        echo '删除数据:' . PHP_EOL . $strDeleteAll . PHP_EOL;
        //执行语句
        $trans = $conn2->beginTransaction();
        try {
            if (!empty($strDeleteAll)) {
                $conn2->createCommand($strDeleteAll)->execute();
            }
            if (!empty($strInsertAll)) {
                $conn2->createCommand($strInsertAll)->execute();
            }
            if (!empty($strUpdateAll)) {
                $conn2->createCommand($strUpdateAll)->execute();
            }
            $trans->commit();
            echo '本次更新成功!' . PHP_EOL;
        } catch (Exception $ex) {
            $trans->rollBack();
            echo '异常:' . $ex . PHP_EOL;
        }

        $t2 = microtime(true);
        echo '执行耗时' . round($t2 - $t1, 3) . '秒' . PHP_EOL;
    }
}